import { useState, useEffect } from 'react'
import { SelectInput } from 'tdesign-react'
import { SearchIcon } from 'tdesign-icons-react'
import type { CheckboxGroupProps, SelectInputProps, RadioGroupProps } from 'tdesign-react'
import SelectionsPanel from './SelectionsPanel'
import { ApiRequest, apis } from '@/service'
import '../index.less'

const {
  getDictionaryArray,
  getCustomizeDictionaryArray,
} = apis.BMService.system

type PropsType = {
  label?: string, // 弹出层的标题
  value?: any[],
  onChange?: (value: any[]) => void,
  multiple?: boolean, // 是否多选
  dictionary?: string, // 字典id 用于获取字典
  extendsInfo?: any, // 扩展信息 用于限定字典的获取条件
  dictionaryTitle?: any[], // 字典title
  placeholder?: string, // placeholder
  filterKeyList?: string[], // ['label'], 可以不传
  sort?: any[], // [{ key: 'value', order: 1 }], 可以不传
  paging?: boolean, // 是否分页 可以不传
  isCustomize?: boolean // 是否自定义
}

const SearchSelect = (props: PropsType) => {

  const {
    value = [], // radio [{ label: , value: }] checkbox [{}, {}, {}]
    onChange = () => {},
    multiple = false,
    dictionary = '',
    extendsInfo = undefined,
    dictionaryTitle = [
      {
        label: props.label,
        labelKey: 'label',
        valueKey: 'value'
      },
    ],
    placeholder = '请选择或输入搜索',
    filterKeyList = undefined, // ['label'], // 可以不传 字典默认使用 label 模糊搜索
    sort = undefined, // [{ key: 'value', order: 1 }], // 可以不传 默认使用 value 升序
    paging = true,
    isCustomize = false,
  } = props

  const [searchValue, setSearchValue] = useState('')
  const [dictionaryArray, setDictionaryArray] = useState<DictionaryListType>([])
  const [popupVisible, setPopupVisible] = useState(false)
  const [pagination, setPagination] = useState<PageParamsType>({
    current: 1,
    pageSize: 5,
    paging: paging
  })
  const [total, setTotal] = useState(0)

  useEffect(() => {
    if (popupVisible && extendsInfo) {
      if (extendsInfo.value?.[0]) {
        QueryDictionaryArray()
      } else {
        setDictionaryArray([])
      }
    } else {
      popupVisible && dictionary && QueryDictionaryArray()
    }
  }, [popupVisible, dictionary, pagination, searchValue, extendsInfo])

  const QueryDictionaryArray = () => {
    if (isCustomize) {
      const params: QueryParamsType = {
        dictionaryValue: dictionary,
        extendsInfo,
        ...pagination,
        keyword: searchValue,
        filterKeyList,
        sort, // 可以不传
      }
      console.log(params)
      ApiRequest({ api: getCustomizeDictionaryArray, params }).then((res: any) => {
        const { code = -1, data = [], total = 0 } = res
        if (code > 0) {
          setDictionaryArray(data)
          setTotal(total)
        } else {
          setDictionaryArray([])
          setTotal(0)
          console.error('获取字典失败')
        }
      }).catch((err: any) => {
        console.error('获取字典失败', err)
      })
    } else {
      const params: QueryParamsType = {
        dictionaryValue: dictionary,
        extendsInfo,
        ...pagination,
        keyword: searchValue,
        filterKeyList,
        sort, // 可以不传
      }
      ApiRequest({ api: getDictionaryArray, params }).then((res: any) => {
        const { code = -1, data = [], total = 0 } = res
        if (code > 0) {
          setDictionaryArray(data)
          setTotal(total)
        } else {
          setDictionaryArray([])
          setTotal(0)
          console.error('获取字典失败')
        }
      }).catch((err: any) => {
        console.error('获取字典失败', err)
      })
    }
  }

  const onTagChange: SelectInputProps['onTagChange'] = (_currentTags, context) => {
    const { trigger, index = 0 } = context
    if (trigger === 'clear') {
      onChange([])
    }
    if (['tag-remove', 'backspace'].includes(trigger)) {
      const newValue = [...value]
      newValue.splice(index, 1)
      onChange(newValue)
    }
  }

  const getDisplayOptions = () => {
    let _displayOptions = dictionaryArray.filter((item: any) => {
      return (filterKeyList || ['label']).some((key: any) => (item[key])?.includes(searchValue))
    })
    return _displayOptions
  }

  const displayOptions = getDisplayOptions()

  const onInputChange: SelectInputProps['onInputChange'] = (inputValue: string) => {
    setSearchValue(inputValue)
    setPopupVisible(true)
  }

  const onInputEnter = () => {
    setSearchValue('')
  }

  const onCheckboxChange: CheckboxGroupProps['onChange'] = (selectedValue: any, { current, type }) => {
    console.log(selectedValue, current, type)
    // current 不存在，则表示操作全选
    if (!current) {
      if (type === 'check') {
        let newValue = displayOptions.slice(0)
        onChange(value.concat(newValue))
      } else if (type === 'uncheck') {
        let newValue = []
        for (let i = 0, len = value.length; i < len; i++) {
          let isExist = false
          for (let displayIndex = 0, len2 = displayOptions.length; displayIndex < len2; displayIndex++) {
            if (value[i].value === displayOptions[displayIndex].value) {
              isExist = true
              break
            }
          }
          if (!isExist) {
            newValue.push(value[i])
          }
        }
        onChange(newValue)
      }
      return
    }
    // 普通操作
    if (type === 'check') {
      const option = dictionaryArray.find((item) => item.value === current)
      onChange(value.concat(option))
    } else {
      const newValue = value.filter((item: any) => item.value !== current)
      onChange(newValue)
    }
  }

  const onRadioChange: RadioGroupProps['onChange'] = (selectedValue: any) => {
    const option = dictionaryArray.find((item) => item.value === selectedValue)
    console.log('option', [option])
    onChange([option])
    setPopupVisible(false)
  }

  /**
   * 获取当前分页的选项值
   * @returns
   */
  const getSelectedValue = () => {
    const arr = []
    for (let i = 0, len1 = displayOptions.length; i < len1; i++) {
      for (let j = 0, len2 = value.length; j < len2; j++) {
        if (displayOptions[i].value === value[j].value) {
          arr.push(displayOptions[i].value)
        }
      }
    }
    return arr
  }

  const selectedValue = getSelectedValue()

  const onPageChange = (pageInfo: PageInfo) => {
    setPagination({
      ...pagination,
      current: pageInfo.current,
    })
  }

  return <div className='aio-form-item-search-select'>
    <SelectInput
      value={value} // value = [{label, value}]
      allowInput={true}
      inputValue={searchValue}
      placeholder={placeholder}
      popupVisible={popupVisible}
      popupProps={{ overlayStyle: { maxHeight: '400px', overflow: 'auto' } }}
      minCollapsedNum={2}
      panel={
        <SelectionsPanel
          multiple={multiple}
          searchValue={searchValue}
          selectedValue={selectedValue}
          dictionaryArray={dictionaryArray}
          displayOptions={displayOptions}
          dictionaryTitle={dictionaryTitle}
          filterKeyList={filterKeyList}
          onCheckboxChange={onCheckboxChange}
          onRadioChange={onRadioChange}
          pageChangedCallback={onPageChange}
          total={total}
        />
      }
      suffixIcon={<SearchIcon />}
      clearable
      multiple
      onTagChange={onTagChange}
      onInputChange={onInputChange}
      onEnter={onInputEnter}
      onBlur={() => { setPopupVisible(false) }}
      onFocus={() => { setPopupVisible(true) }}
    />
  </div>
}

export default SearchSelect
